#!/bin/bash
# -*- encoding: utf8 -*-
import datetime

from BModel.md5Hive import md5Encode
from config.config import reviewfile, max_count_windows
from core.common import send_warning_msg
import time

def AddDataInsertHive(db):
    time_start = time.time()
    print reviewfile
    fp = open(max_count_windows,'r')
    lastid = fp.readline()
    fp.close()
    try:
        oldsql = "SELECT ID,ReviewID,OrderID FROM `bw_ctrip_review_cn_v2` WHERE ID >(%s)"%(lastid)
    except:
        errMsg = '数据库读取失败'
        send_warning_msg("新增订单数据存储", "新增订单数据存储", "不正常", errMsg)
    data = db.bmquery(oldsql,'ctripn')
    insertsql,stip,maxid= "","",0
    now_time = datetime.datetime.now()
    yes_time = now_time + datetime.timedelta(days=-1)
    add_time = yes_time.strftime('%Y%m%d')
    if True == data['status']:
        for v in data['data']:
            maxid = v['ID']
            insertsql = insertsql+stip +"(%s,'%s','%s')"%(v['ReviewID'], md5Encode(v['OrderID']), add_time)
            stip = ","

    allcount = int(maxid) - int(lastid)
    print allcount
    if insertsql:
        hotelsql = "INSERT INTO BW_Order_Review_List(`ReviewID`,`OrderID`,`DateTime`) VALUES%s"%(insertsql)
        db.bmquery(hotelsql,'hive')
        time_end = time.time()
        LengthTime = time_end - time_start
        errMsg = '新增订单数据存储%s条\n用时%ss' % (allcount, LengthTime)
        send_warning_msg("新增订单数据存储", "新增订单数据存储", "正常", errMsg)
    #
    if 0 < maxid:
        fp = open(max_count_windows,'w+')
        fp.write(str(maxid))
        fp.close()


